import { useDark, useToggle } from '@vueuse/core'

export const useTheme = () => {
  const isDark = useDark({
    storageKey: '__theme__',
  })
  const toggleDark = useToggle(isDark)

  // 切换暗黑模式
  const changeDark = () => {
    const el = document.getElementById('themeToggleBtn') as Element
    const transition = document.startViewTransition(() => {
      toggleDark()
    })

    transition.ready.then(() => {
      const rect = el.getBoundingClientRect()
      const x = rect.left + rect.width / 2
      const y = rect.top + rect.height / 2
      const endRadius = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y))
      const clipPath = [
        `circle(0 at ${x}px ${y}px)`,
        `circle(${endRadius}px at ${x}px ${y}px)`,
      ]
      document.documentElement.animate(
        {
          clipPath: isDark.value ? clipPath.reverse() : clipPath,
        },
        {
          duration: 400,
          pseudoElement: isDark.value
            ? '::view-transition-old(root)'
            : '::view-transition-new(root)',
        },
      )
    })
  }
  return {
    isDark,
    changeDark,
  }
}
